package cn.iocoder.yudao.module.stock.mq.mq.consumer;

import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.stock.dal.dataobject.stock.StockDO;

import cn.iocoder.yudao.module.stock.mq.message.StockInfoSendMessage;
import cn.iocoder.yudao.module.stock.mq.mq.producer.StockInfoSendProducer;
import cn.iocoder.yudao.module.stock.service.stock.StockService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;
import cn.iocoder.yudao.module.orderview.mq.message.OrderViewTaskMessage;
import javax.annotation.Resource;

/**
 * 针对 {@link OrderViewTaskMessage} 的消费者
 *
 * @author 徐煜东
 */
@RocketMQMessageListener( // 重点：添加 @RocketMQMessageListener 注解，声明消费的 topic
        topic = OrderViewTaskMessage.TOPIC,
        consumerGroup = OrderViewTaskMessage.TOPIC + "_STOCK_CONSUMER"
)
@Component
@Slf4j
public class OrderViewTaskConsumer implements RocketMQListener<OrderViewTaskMessage> {
    @Resource
    StockService stockService;
    @Resource
    StockInfoSendProducer stockInfoSendProducer;

    @Override
    public void onMessage(OrderViewTaskMessage message) {
        log.info("[onMessage][消息内容({})]", message);
        //数据库查询product信息
        StockDO stock = stockService.getStockByProductId(message.getProductId());
        log.info("[onMessage][查询商品库存信息成功，结果为({})]", stock);
        if (stock == null) {
            log.warn("[onMessage][商品不存在，不需要重试，直接跳过] productId={}", message.getProductId());
            return; // 不抛异常，直接结束消费
        }
        StockInfoSendMessage stockInfoSendMessage = new StockInfoSendMessage();
        BeanUtils.copyProperties(stock, stockInfoSendMessage);
        stockInfoSendMessage.setRequestId(message.getRequestId());
        stockInfoSendMessage.setProductId(message.getProductId());
        // 查询商品信息推送到mq
        stockInfoSendProducer.sendStockInfoMessage(stockInfoSendMessage);
        log.info("[onMessage][发送商品促销信息成功]");

    }
}
